package cn.chenxing.module.login.controller;

import cn.chenxing.domain.threadlocal.ThreadLocalInfo;
import cn.chenxing.domain.util.DialogBuilderUtil;
import cn.chenxing.domain.util.EnDecodeUtil;
import cn.chenxing.constant.VenusConstant;
import cn.chenxing.module.login.service.LoginService;
import cn.chenxing.module.login.view.ForgetView;
import cn.chenxing.module.login.view.RegisterView;
import cn.chenxing.module.main.view.MainView;
import cn.chenxing.module.user.entity.VenusUserInfoEntity;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.validation.RequiredFieldValidator;
import de.felixroske.jfxsupport.FXMLController;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.kordamp.ikonli.fontawesome5.FontAwesomeSolid;
import org.kordamp.ikonli.javafx.FontIcon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * @Description 登录Controller层
 * @Author maogen.ymg
 * @Date 2020/2/27 22:45
 */
@Lazy
@FXMLController
@Slf4j
public class LoginController implements Initializable {

    @FXML
    private JFXTextField userName;

    @FXML
    private JFXPasswordField password;

    @FXML
    private Label systemTime;

    @FXML
    private JFXButton loginButton;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RegisterView registerView;

    @Autowired
    private ForgetView forgetView;

    @Autowired
    private MainView mainView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 系统时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final Timeline timeline = new Timeline(
                new KeyFrame(
                        Duration.millis(500),
                        event -> systemTime.setText(sdf.format(new Date()))
                )
        );
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();

        // 验证是否输入
        RequiredFieldValidator validator = new RequiredFieldValidator();
        validator.setMessage("Please enter content");
        // 警告图标
        FontIcon warnIcon = new FontIcon(FontAwesomeSolid.EXCLAMATION_TRIANGLE);
        warnIcon.getStyleClass().add("error");
        validator.setIcon(warnIcon);

        userName.getValidators().add(validator);
        userName.focusedProperty().addListener((o, oldVal, newVal) -> {
            if (!newVal) {
                userName.validate();
            }
        });
        password.getValidators().add(validator);
        password.focusedProperty().addListener((o, oldVal, newVal) -> {
            if (!newVal) {
                password.validate();
            }
        });

    }

    @FXML
    protected void login() {
        // 检查内容完整性
        if(!StringUtils.isNoneBlank(userName.getText(), password.getText())) {
            DialogBuilderUtil.showPositiveAlert(loginButton, "请注意", "请完整填写账号和密码");
            return;
        }

        // 密码MD5加密
        VenusUserInfoEntity userInfoEntity = new VenusUserInfoEntity();
        userInfoEntity.setUserName(userName.getText().trim())
                .setPassword(EnDecodeUtil.md5(password.getText().trim()));

        // 登录成功，进入主界面
        if(loginService.login(userInfoEntity, loginButton)){
            // Fxml读入方式：newStageByFxml(LoginConstant.MAIN_FXML_PATH)
            // 保存当前登录用户名
            ThreadLocalInfo.get().setUserName(userInfoEntity.getUserName());
            loginService.newStageByView(mainView);
            operateWindow(userName.getScene().getWindow(), "close");
        }

    }

    @FXML
    private void register() {
        Window loginWindow = userName.getScene().getWindow();
        // 保存当前登录窗口
        ThreadLocalInfo.get().setPreviousWindow(loginWindow);
        // 新建在前, 关闭隐藏在后
        loginService.newStageByView(registerView, VenusConstant.REGISTER_TITLE, loginWindow);
        operateWindow(loginWindow, "hide");
    }

    @FXML
    private void forget() {
        Window loginWindow = userName.getScene().getWindow();
        // 保存当前登录窗口
        ThreadLocalInfo.get().setPreviousWindow(loginWindow);
        // 新建在前, 关闭隐藏在后
        loginService.newStageByView(forgetView, VenusConstant.FORGET_TITLE, loginWindow);
        operateWindow(loginWindow, "hide");
    }

    /**
     * 窗口-----关闭，显示，隐藏
     * @param window 窗口
     * @param operate 操作类型
     */
    private void operateWindow(Window window, String operate) {
        Stage stage =(Stage) window;
        switch (operate){
            case "show":
                stage.show(); break;
            case "hide":
                stage.hide(); break;
            case "close":
            default:
                stage.close(); break;
        }
    }

}
